package com.dson.user.controller;

import com.dson.common.CookieUtil;
import com.dson.common.LagouResponse;
import com.dson.common.pojo.UserResult;
import com.dson.common.service.AuthCodeService;
import com.dson.common.service.UserService;
import com.dson.user.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final String LG_U_TOKEN = "lg_u_token";

    @Reference
    private UserService userService;

    @Reference
    private AuthCodeService authCodeService;

    @GetMapping("/register/{email}/{password}/{code}")
    public LagouResponse register(@PathVariable("email") String email,
                                  @PathVariable("password") String password,
                                  @PathVariable("code") String code,
                                  HttpServletResponse response) {
        Integer checkCodeResponse = authCodeService.checkCode(email, code);
        if (checkCodeResponse == 0) {
            return LagouResponse.failure("注册失败");
        }
        if (userService.checkEmail(email)) {
            return LagouResponse.failure("邮箱已注册");
        }
        UserResult user = userService.register(email, password);
        if (user == null) {
            return LagouResponse.failure("注册失败");
        }
        CookieUtil.setCookie(response, LG_U_TOKEN, user.getToken(), "localhost");
        return LagouResponse.success(email);
    }

    @GetMapping("/isRegistered/{email}")
    public LagouResponse isRegistered(@PathVariable("email") String email) {
        boolean result = userService.checkEmail(email);
        if (result) {
            return LagouResponse.success("邮箱已注册");
        }
        return LagouResponse.failure("邮箱未注册");
    }

    @GetMapping("/login/{email}/{password}")
    public LagouResponse login(@PathVariable("email") String email,
                               @PathVariable("password") String password,
                               HttpServletResponse response) {
        UserResult user = userService.login(email, password);
        if (user == null) {
            return LagouResponse.failure("邮箱或密码错误");
        }
        CookieUtil.setCookie(response, LG_U_TOKEN, user.getToken(), "localhost");
        return LagouResponse.success(email);
    }

    @GetMapping("/info/{token}")
    public LagouResponse checkToken(@PathVariable("token") String token) {
        UserResult user = userService.verifyToken(token);
        if (user == null) {
            return LagouResponse.failure("用户不存在");
        }
        return LagouResponse.success(user.getEmail());
    }
}
